package com.ishow.noah.modules.main

import android.app.Application
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.ishow.noah.entries.App
import com.ishow.noah.modules.base.mvvm.viewmodel.AppBaseViewModel
import java.util.*

/**
 * Created by yuhaiyang on 2020-01-02.
 */
class MainViewModel(app: Application) : AppBaseViewModel(app) {

    private val _appList = MutableLiveData<MutableList<App>>()
    val appList: LiveData<MutableList<App>>
        get() = _appList

    private val allAppList = mutableListOf<App>()

    init {
        getAppList()
    }

    private fun getAppList() {
        val pm: PackageManager = context.packageManager

        val filterIntent = Intent(Intent.ACTION_MAIN)
        filterIntent.addCategory(Intent.CATEGORY_LAUNCHER)
        val appList = pm.queryIntentActivities(filterIntent, 0)

        val result: MutableList<App> = ArrayList()
        for (app in appList) {
            result.add(getAppInfo(app))
        }
        allAppList.addAll(result)
        _appList.value = allAppList
    }


    fun search(keyword: String) {
        if (keyword.isEmpty()) {
            _appList.value = allAppList
        } else {
            val list = allAppList.filter { it.title?.contains(keyword) ?: false }
            _appList.value = list.toMutableList()
        }
    }

    private fun getAppInfo(info: ResolveInfo): App {
        val appInfo = info.activityInfo.applicationInfo
        val pm: PackageManager = context.packageManager
        val app = App()
        app.title = appInfo.loadLabel(pm) as String
        app.icon = appInfo.loadIcon(pm)
        app.minSdkVersion = appInfo.minSdkVersion
        app.targetSdkVersion = appInfo.targetSdkVersion
        app.packageName = appInfo.packageName
        app.launchClass = info.activityInfo.name
        return app
    }
}